import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { motion, AnimatePresence } from 'framer-motion';
import { useNavigate } from 'react-router-dom';
import backIcon from '../assets/images/back-icon.png';

// 心理小知识的数据结构
interface Knowledge {
  id: number;
  title: string;
  content: string;
}

// 模拟的后端API数据
const mockKnowledgeData: Knowledge[] = [
  {
    id: 1,
    title: '什么是正念？',
    content: '正念（Mindfulness）是一种心理过程，旨在通过有意识地、不加评判地将注意力集中于当下，来提高自我意识。练习正念可以帮助减轻压力、改善情绪、提高专注力。',
  },
  {
    id: 2,
    title: '认知行为疗法 (CBT)',
    content: '认知行为疗法是一种常见的心理治疗方法，它帮助人们识别并改变消极或破坏性的思维模式和行为。CBT 被广泛用于治疗抑郁症、焦虑症等多种心理问题。',
  },
  {
    id: 3,
    title: '"心流"状态的力量',
    content: '心流（Flow）是指当一个人完全沉浸在某项活动中时，所体验到的一种精神状态。在这种状态下，人会感到精力充沛、全神贯注、并且享受其中。主动寻求心流体验有益于提升幸福感。',
  },
  {
    id: 4,
    title: '睡眠对心理健康的重要性',
    content: '充足的睡眠对于情绪调节、认知功能和整体心理健康至关重要。长期睡眠不足会增加患上焦虑和抑郁等心理疾病的风险。',
  },
  {
    id: 5,
    title: '情绪的"冰山理论"',
    content: '萨提亚的冰山理论认为，人的行为和情绪（冰山一角）只是表面现象，其下隐藏着更深层次的感受、观点、期待和渴望。理解这一点有助于我们更深刻地理解自己和他人。',
  },
];

// Framer Motion Variants (与 home.tsx 保持一致)
const pageVariants = {
  initial: { opacity: 0 },
  in: { opacity: 1, transition: { staggerChildren: 0.1, duration: 0.4 } },
  out: { opacity: 0 }
};

const cardVariants = {
  initial: { opacity: 0, y: 30, scale: 0.98 },
  in: { opacity: 1, y: 0, scale: 1, transition: { duration: 0.5, ease: [0.25, 1, 0.5, 1] } },
  out: { opacity: 0, y: -20, scale: 0.95 }
};

// Styled Components (大部分从 home.tsx 复用)
const PageContainer = styled(motion.div)`
  min-height: 100vh;
  width: 100vw;
  background: linear-gradient(135deg, #e0f7fa 0%, #b3e5fc 100%);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  padding-top: 90px;
  box-sizing: border-box;
  position: relative;
  font-family: 'Roboto', 'Helvetica Neue', Arial, sans-serif;
`;

const Header = styled(motion.header)`
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  padding: 20px 0;
  background-color: rgba(255, 255, 255, 0.65);
  backdrop-filter: blur(12px);
  box-shadow: 0 3px 12px rgba(0, 0, 0, 0.07);
  z-index: 1000;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
`;

const BackButton = styled(motion.img)`
  position: absolute;
  left: 25px;
  top: 50%;
  transform: translateY(-50%);
  width: 22px;
  height: 22px;
  cursor: pointer;
  opacity: 0.7;
  transition: opacity 0.2s ease-in-out, transform 0.2s ease-in-out;

  &:hover {
    opacity: 1;
    transform: translateY(-50%) scale(1.1);
  }
`;

const Title = styled(motion.h1)`
  font-size: 1.5rem;
  color: #2c3e50;
  font-weight: 500;
  margin: 0;
`;

const ContentWrapper = styled(motion.div)`
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  max-width: 800px;
  gap: 28px;
`;

const KnowledgeCard = styled(motion.section)`
  background: rgba(255, 255, 255, 0.6);
  backdrop-filter: blur(15px);
  border-radius: 18px;
  padding: 28px;
  width: 100%;
  box-shadow: 0 10px 35px rgba(0, 0, 0, 0.08);
  
  h2 {
    font-size: 1.4rem;
    color: #34495e;
    margin-top: 0;
    margin-bottom: 18px;
    border-bottom: 1px solid rgba(52, 73, 94, 0.1);
    padding-bottom: 12px;
    font-weight: 500;
  }
  p {
    font-size: 1rem;
    color: #5a6a7a;
    line-height: 1.7;
    white-space: pre-wrap; // 保持文本格式
  }
`;

const LoadingDisplay = styled(motion.div)`
  display: flex;
  justify-content: center;
  align-items: center;
  height: calc(100vh - 90px - 40px);
  font-size: 1.2rem;
  color: #007bff;
  width: 100%;
`;

const ErrorDisplay = styled(motion.div)`
  color: #c0392b;
  background-color: rgba(231, 76, 60, 0.08);
  width: 100%;
  max-width: 650px;
  margin-bottom: 25px;
  padding: 18px 22px;
  border: 1px solid rgba(192, 57, 43, 0.2);
  border-radius: 12px;
  white-space: pre-wrap;
  text-align: center;
  font-size: 0.9rem;
`;

const KnowPage: React.FC = () => {
  const navigate = useNavigate();
  const [knowledgeItems, setKnowledgeItems] = useState<Knowledge[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchKnowledge = async () => {
      try {
        // 模拟 API 请求
        await new Promise(resolve => setTimeout(resolve, 1000));
        
        // 在实际应用中，这里会是 fetch('/api/knowledge') 之类的调用
        // 假设API返回的数据结构是 { code: 200, data: [...] }
        setKnowledgeItems(mockKnowledgeData);

      } catch (err) {
        setError('加载心理知识失败，请稍后再试。');
        console.error(err);
      } finally {
        setLoading(false);
      }
    };

    fetchKnowledge();
  }, []);

  const handleBack = () => {
    navigate(-1); // 返回上一页
  };

  return (
    <PageContainer
      initial="initial"
      animate="in"
      exit="out"
      variants={pageVariants}
    >
      <Header>
        <BackButton 
          src={backIcon} 
          alt="Back" 
          onClick={handleBack}
          whileHover={{ scale: 1.1 }}
          whileTap={{ scale: 0.9 }}
        />
        <Title>心理小知识</Title>
      </Header>

      <ContentWrapper>
        <AnimatePresence>
          {loading && (
            <LoadingDisplay key="loading">正在加载...</LoadingDisplay>
          )}

          {error && (
            <ErrorDisplay key="error">{error}</ErrorDisplay>
          )}

          {!loading && !error && knowledgeItems.map(item => (
            <KnowledgeCard
              key={item.id}
              variants={cardVariants}
              initial="initial"
              animate="in"
              exit="out"
              layout
            >
              <h2>{item.title}</h2>
              <p>{item.content}</p>
            </KnowledgeCard>
          ))}
        </AnimatePresence>
      </ContentWrapper>
    </PageContainer>
  );
};

export default KnowPage;
